//

//  RecommentViewController.m

//  BuffetNews

//

//  Created by 李荃荃 on 14-10-27.

//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.

//



#import "RecommentViewController.h"
#import "MBProgressHUD.h"
#import "NetHandler.h"
#import "TextCell.h"
#import "OnePicCell.h"
#import "ThreePicCell.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "CommentViewController.h"
#import "CompareDate.h"
#import "NightModel.h"
#import "Reachability.h"
#import <SystemConfiguration/SystemConfiguration.h>
@interface RecommentViewController ()<UITableViewDelegate, UITableViewDataSource, UIScrollViewDelegate>

@property (nonatomic, retain) UITableView *mainTV;
@property (nonatomic, retain) MBProgressHUD *hud;
@property (nonatomic, retain) NSMutableArray *arrNews;
@property (nonatomic, retain) NSArray *countPic;
@property (nonatomic, retain) NSArray *countPic1;
@property (nonatomic, retain) NSArray *allArr;
@property (nonatomic, retain) NSMutableArray *sumArr;
@property (nonatomic, retain) NSMutableArray *sarr;
@property (nonatomic, retain) NSMutableArray *barr;
@property (nonatomic, retain) NSMutableSet *rankSet;
@property (nonatomic, retain) UILabel *label;

//自定义cell
@property (nonatomic, retain) OnePicCell *cell;
@property (nonatomic, retain) TextCell *noCell;
@property (nonatomic, retain) ThreePicCell *threeCell;
@property (nonatomic, assign) NSInteger receive;


@end



@implementation RecommentViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    
    if (self) {
        self.barr = [NSMutableArray array];
        self.sarr = [NSMutableArray array];
        self.rankSet = [NSMutableSet set];
        self.arrNews = [NSMutableArray array];
        self.countPic = [NSArray array];
        self.allArr = [NSArray array];
        self.sumArr = [NSMutableArray array];
        self.mainTV = [[UITableView alloc]init];


        // Custom initialization
    }
    return self;
    
}

- (void)dealloc
{
    [_barr release];
    [_sarr release];
    [_rankSet release];
    [_arrNews release];
    [_countPic release];
    [_allArr release];
    [_sumArr release];
    [_mainTV release];
    [_cell release];
    [_noCell release];
    [_threeCell release];
    [_countPic1 release];
    [_hud release];
    [_label release];
    [super dealloc];

}

- (void)viewWillAppear:(BOOL)animated
{
    [self.mainTV reloadData];
}
- (void)viewDidLoad

{
    [super viewDidLoad];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    titleLabel.text = @"热点";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    [self drawView];
    [self setupRefresh];
    NSNotificationCenter *notification = [NSNotificationCenter defaultCenter];
    [notification addObserver:self selector:@selector(receiveNotification:) name:@"Night" object:nil];
}
#pragma 消息中心的夜间模式
- (void)receiveNotification:(NSNotification *)notification
{
//    self.receive = [notification.object integerValue];
    self.receive = [NightModel shareInstance].open;
    NSLog(@"我是单例%d",[NightModel shareInstance].open);
    if ([NightModel shareInstance].open == 1) {
        self.mainTV.backgroundColor = [UIColor grayColor];
        self.view.backgroundColor = [UIColor blackColor];
    }else{
        self.mainTV.backgroundColor = [UIColor whiteColor];
            self.view.backgroundColor = [UIColor whiteColor];
    }
    [_mainTV reloadData];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    if (velocity.y > 0) {
        self.navigationController.navigationBarHidden = YES;
        self.mainTV.frame = CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20);
    }else{
        self.navigationController.navigationBarHidden = NO;
        self.mainTV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }

}
- (void)drawView

{
    //绘制界面
    self.navigationController.navigationBar.translucent = NO;
    self.mainTV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 114);
    self.mainTV.dataSource = self;
    self.mainTV.delegate = self;
    [self.view addSubview:self.mainTV];
    [self.mainTV release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrNews.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

{
    self.countPic = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"media"];
    if (self.countPic.count == 2 || self.countPic.count == 1) {
        
        _cell = [tableView dequeueReusableCellWithIdentifier:@"onecell"];
        if (_cell == nil) {
            _cell = [[[OnePicCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"onecell"]autorelease];
        }
        NSString *str = [[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"special_info"]objectForKey:@"icon_url"];
        
        if ([str length] != 0) {
            [_cell.hotView sd_setImageWithURL:[NSURL URLWithString:str]];
        }else{
            [_cell.hotView removeFromSuperview];
         NSString *timeStr = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"date"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
            [formatter setLocale:enLocale];
            [enLocale release];
            
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *dateTime = [formatter dateFromString:timeStr];
            
            NSString *strTime = [CompareDate compareCurrentTime:dateTime];
            _cell.timeLabel.text = strTime;
            _cell.timeLabel.font = [UIFont systemFontOfSize:10];
            [formatter release];
            [enLocale release];
        }
        
        _cell.titleLabel.text = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"title"];
        _cell.titleLabel.numberOfLines = 0;
        _cell.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold"  size:17];
        
        _cell.auther_name.text = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"auther_name"];
        _cell.auther_name.font = [UIFont systemFontOfSize:10];
        NSString *strPic = [[_countPic objectAtIndex:0]objectForKey:@"m_url"];
        [_cell.oneView sd_setImageWithURL:[NSURL URLWithString:strPic]];
        
        //夜间模式开启 变身
        if (self.receive == 1) {
            _cell.backgroundColor = [UIColor blackColor];
            _cell.titleLabel.textColor = [UIColor grayColor];
            _cell.auther_name.textColor = [UIColor grayColor];
        }else{
            _cell.backgroundColor = [UIColor whiteColor];
            _cell.titleLabel.textColor = [UIColor blackColor];
            _cell.auther_name.textColor = [UIColor blackColor];
        }
        _cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return _cell;
    }else if(_countPic.count >= 3){
        _threeCell = [tableView dequeueReusableCellWithIdentifier:@"threecell"];
        if (_threeCell == nil) {
            
            _threeCell = [[[ThreePicCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"threecell"]autorelease];
        }
        NSString *str = [[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"special_info"]objectForKey:@"icon_url"];
        if ([str length] != 0) {
            [_threeCell.hotView sd_setImageWithURL:[NSURL URLWithString:str]];
        }else{
            [_threeCell.hotView removeFromSuperview];
            NSString *timeStr = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"date"];
            NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
            NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
            [formatter setLocale:enLocale];
            [enLocale release];
            
            [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
            NSDate *dateTime = [formatter dateFromString:timeStr];
            
            NSString *strTime = [CompareDate compareCurrentTime:dateTime];
            _threeCell.timeLabel.text = strTime;
            _threeCell.timeLabel.font = [UIFont systemFontOfSize:10];
        }
        
        _threeCell.titleLabel.text = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"title"];
        _threeCell.titleLabel.numberOfLines = 0;
        _threeCell.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold"  size:17];

        _threeCell.auther_name.text = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"auther_name"];
        _threeCell.auther_name.font = [UIFont systemFontOfSize:10];
        
        NSString *strPic0 = [[_countPic objectAtIndex:0]objectForKey:@"m_url"];
        NSString *strPic1 = [[_countPic objectAtIndex:1]objectForKey:@"m_url"];
        NSString *strPic2 = [[_countPic objectAtIndex:2]objectForKey:@"m_url"];
        
        [_threeCell.oneView sd_setImageWithURL:[NSURL URLWithString:strPic0]];
        [_threeCell.twoView sd_setImageWithURL:[NSURL URLWithString:strPic1]];
        [_threeCell.threeView sd_setImageWithURL:[NSURL URLWithString:strPic2]];
        
        if (self.receive == 1) {
            _threeCell.backgroundColor = [UIColor blackColor];
            _threeCell.titleLabel.textColor = [UIColor grayColor];
            _threeCell.auther_name.textColor = [UIColor grayColor];
        }else{
            _threeCell.backgroundColor = [UIColor whiteColor];
            _threeCell.titleLabel.textColor = [UIColor blackColor];
            _threeCell.auther_name.textColor = [UIColor blackColor];
        }
        _threeCell.selectionStyle = UITableViewCellSelectionStyleNone;

        return _threeCell;

    }else{
    _noCell = [tableView dequeueReusableCellWithIdentifier:@"nocell"];
    if (_noCell == nil) {
        _noCell = [[[TextCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"nocell"]autorelease];
    }
    NSString *str = [[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"special_info"]objectForKey:@"icon_url"];
    if ([str length] != 0) {
        [_noCell.hotView sd_setImageWithURL:[NSURL URLWithString:str]];
    }else{
        [_noCell.hotView removeFromSuperview];
        NSString *timeStr = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"date"];
        NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
        NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en-US"];
        [formatter setLocale:enLocale];
        [enLocale release];
        
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *dateTime = [formatter dateFromString:timeStr];
        
        NSString *strTime = [CompareDate compareCurrentTime:dateTime];
        _noCell.timeLabel.text = strTime;
        _noCell.timeLabel.font = [UIFont systemFontOfSize:10];
    }
    _noCell.titleLabel.text = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"title"];
    _noCell.titleLabel.numberOfLines = 0;
    _noCell.titleLabel.font = [UIFont fontWithName:@"Helvetica-Bold"  size:17];
    
    _noCell.auther_name.text = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"auther_name"];
    _noCell.auther_name.font = [UIFont systemFontOfSize:10];
    
    }
    
    if (self.receive == 1) {
        _noCell.backgroundColor = [UIColor blackColor];
        _noCell.titleLabel.textColor = [UIColor grayColor];
        _noCell.auther_name.textColor = [UIColor grayColor];
    }else{
        _noCell.backgroundColor = [UIColor whiteColor];
        _noCell.titleLabel.textColor = [UIColor blackColor];
        _noCell.auther_name.textColor = [UIColor blackColor];
    }
    _noCell.selectionStyle = UITableViewCellSelectionStyleNone;
    return _noCell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = @{NSFontAttributeName :[UIFont systemFontOfSize:17]};
    CGRect rect = [[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"title"] boundingRectWithSize:CGSizeMake(self.view.frame.size.width, 0) options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    
    if ([[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"media"] count] == 0) {
        return (rect.size.height + 50);
    }if ([[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"media"] count] == 1 || [[[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"media"] count] == 2) {
        return (rect.size.height + 70);
    }
    else{
        return (rect.size.height + 120);
    }
}
- (void)setupRefresh
{
//     1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.mainTV addHeaderWithTarget:self action:@selector(headerRereshing)];
    [self.mainTV headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.mainTV addFooterWithTarget:self action:@selector(footerRereshing)];
    [self.mainTV footerEndRefreshing];
    //
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    self.mainTV.headerPullToRefreshText = @"下拉加载数据...";
    self.mainTV.headerReleaseToRefreshText = @"松开即可加载...";
    self.mainTV.headerRefreshingText = @"数据加载中...";
    
    self.mainTV.footerPullToRefreshText = @"上拉可以加载更多数据了";
    self.mainTV.footerReleaseToRefreshText = @"松开马上加载更多数据了";
    self.mainTV.footerRefreshingText = @"加载中";
    
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    BOOL reachable = [[Reachability reachabilityForInternetConnection] isReachable];
    
    if (!reachable) {
        UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:@"该功能需要连接网络才能使用，请检查您的网络连接状态" message:nil delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil] autorelease];
        [alertView show];
    } else {
        NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *path = [pathArr objectAtIndex:0];
    
        NSString *filePath = [path stringByAppendingPathComponent:@"rootBlocks.plist"];
        NSDictionary *rootDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
        NSArray *arrRank = [rootDic objectForKey:@"blocksData"];
        for (int i = 0; i < 2; i++) {
            NSString *str = [arrRank[(arc4random() % arrRank.count)]objectForKey:@"api_url"];
            [self.rankSet addObject:str];
        }
    for (NSString *setStr in _rankSet) {
        [self.sarr addObject:setStr];
    }
//这个是随机出来新闻的网址
    //循环 遍历请求数据
    for (int i = 0; i < self.sarr.count; i++) {
        [NetHandler networkWithURL:self.sarr[i] comaletion:^(id result) {
            //判断信息是否是空
            if ([[result objectForKey:@"msg"]  isEqual: @"ok"]) {
                //取出data
                NSDictionary *dic = [result objectForKey:@"data"];
                //取出articles 这个里面装着字典 都是网页信息
                NSMutableArray *dicArr = [dic objectForKey:@"articles"];
                for (int i = 0; i < 3; i++) {
                    NSMutableSet *rankSet = [NSMutableSet set];
                    [rankSet addObject:dicArr[(arc4random() % dicArr.count)]];
                    [self.arrNews insertObject:[rankSet anyObject] atIndex:0];
                }
            }

        }];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        
        [self.mainTV reloadData];
        [self.mainTV headerEndRefreshing];
        
        NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(doTime) userInfo:nil repeats:NO];
        NSLog(@"%@", timer);

    });
    }
}

-(BOOL)isReachableViaWWAN
{
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

- (void)doTimeStop
{
    [_label removeFromSuperview];
}
- (void)doTime
{
    _label = [[UILabel alloc]init];
    _label.frame = CGRectMake(0, 0, self.view.frame.size.width, 30);
    NSString *str = [NSString stringWithFormat:@"更新了%d条新闻",
                     self.rankSet.count];
    _label.text =str;
    _label.font = [UIFont boldSystemFontOfSize:14];
    _label.textAlignment = NSTextAlignmentCenter;
    _label.alpha = 0.5;
    _label.backgroundColor = [UIColor blackColor];
    _label.textColor = [UIColor whiteColor];
    [self.view addSubview:_label];
    
            NSTimer *timer1 = [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(doTimeStop) userInfo:nil repeats:NO];
    NSLog(@"%@", timer1);
}
- (void)footerRereshing
{
    
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [pathArr objectAtIndex:0];
    
    NSString *filePath = [path stringByAppendingPathComponent:@"rootBlocks.plist"];
    NSDictionary *rootDic = [NSDictionary dictionaryWithContentsOfFile:filePath];
    NSArray *arrRank = [rootDic objectForKey:@"blocksData"];
    for (int i = 0; i < 5; i++) {
        NSString *str = [arrRank[(arc4random() % arrRank.count)]objectForKey:@"api_url"];
        [self.rankSet addObject:str];
    }
    for (NSString *setStr in _rankSet) {
        [self.barr addObject:setStr];
    }
    
    for (int i = 0; i < self.barr.count; i++) {
        [NetHandler networkWithURL:self.barr[i] comaletion:^(id result) {
            if ([result objectForKey:@"data"] != nil) {
                NSDictionary *dic = [result objectForKey:@"data"];
                
                NSMutableArray *dicArr = [dic objectForKey:@"articles"];
                for (int i = 0; i < 1; i++) {
                    NSMutableSet *rankSet = [NSMutableSet set];
                    [rankSet addObject:dicArr[(arc4random() % dicArr.count)]];
                    [self.arrNews addObject:[rankSet anyObject]];
                }
            }
         }];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.mainTV reloadData];
        [self.mainTV footerEndRefreshing];
    });
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentViewController *comVC = [[CommentViewController alloc]init];
    NSString *webStr = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"weburl"];
    NSString *PKStr = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"pk"];
    NSString *tittle = [[self.arrNews objectAtIndex:indexPath.row]objectForKey:@"title"];
    comVC.webString = webStr;
    comVC.tittle = tittle;
    comVC.pkString = PKStr;
 
//    [self.navigationController pushViewController:comVC animated:YES];

    [comVC setModalTransitionStyle:UIModalTransitionStyleCoverVertical];
    [self presentViewController:comVC animated:YES completion:^{
        
    }];

}
- (void)didReceiveMemoryWarning

{
    
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
    
}



/*
 
 #pragma mark - Navigation
 
 
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 
 {
 
 // Get the new view controller using [segue destinationViewController].
 
 // Pass the selected object to the new view controller.
 
 }
 
 */



@end